package cn.iocoder.an.module.business.service.feedback;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.business.utils.WeComMessageUtil;
import cn.iocoder.an.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.an.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.dict.DictDataService;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.an.module.business.controller.admin.feedback.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.feedback.FeedbackDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.feedback.FeedbackMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 快捷反馈 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class FeedbackServiceImpl implements FeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private AdminUserService userService;

    @Autowired
    private WeComMessageUtil weComMessageUtil;

    @Resource
    private DictDataService dictDataService;

    @Override
    public Long createFeedback(FeedbackSaveReqVO createReqVO) {
        // 插入
        FeedbackDO feedback = BeanUtils.toBean(createReqVO, FeedbackDO.class);
        setOtherData(createReqVO);
        List<Long> ids = createReqVO.getSolveUser();
        ids.add(createReqVO.getDutyUserId());
        if (createReqVO.getResend() == 1) {
            sendKeepMessage(ids);
        }

        feedbackMapper.insert(feedback);

        // 返回
        return feedback.getId();
    }

    @Override
    public void updateFeedback(FeedbackSaveReqVO updateReqVO) {
        // 校验存在
        validateFeedbackExists(updateReqVO.getId());
        setOtherData(updateReqVO);
        // 更新
        List<Long> ids = updateReqVO.getSolveUser();
        ids.add(updateReqVO.getDutyUserId());
        if (updateReqVO.getResend() == 1) {
            sendKeepMessage(ids);
        }
        FeedbackDO updateObj = BeanUtils.toBean(updateReqVO, FeedbackDO.class);
        feedbackMapper.updateById(updateObj);
    }

    @Override
    public void deleteFeedback(Long id) {
        // 校验存在
        validateFeedbackExists(id);
        // 删除
        feedbackMapper.deleteById(id);
    }

    @Override
    public void deleteFeedbackListByIds(List<Long> ids) {
        // 删除
        feedbackMapper.deleteByIds(ids);
    }


    private void validateFeedbackExists(Long id) {
        if (feedbackMapper.selectById(id) == null) {
            throw exception(FEEDBACK_NOT_EXISTS);
        }
    }

    @Override
    public FeedbackDO getFeedback(Long id) {
        FeedbackDO feedbackDO = feedbackMapper.selectById(id);
        setDuration(feedbackDO);
        return feedbackDO;
    }

    @Override
    public PageResult<FeedbackDO> getFeedbackPage(FeedbackPageReqVO pageReqVO) {
        PageResult<FeedbackDO> feedbackDOPageResult = feedbackMapper.selectPage(pageReqVO);
        feedbackDOPageResult.getList().forEach(feedbackDO -> {
            setDuration(feedbackDO);
        });
        return feedbackDOPageResult;
    }

    public void setOtherData(FeedbackSaveReqVO reqVO) {
        List<AdminUserDO> userList = userService.getUserList(reqVO.getSolveUser());
        String dutyUserName = userList.stream()
                .map(AdminUserDO::getNickname)                    // 提取 nickname
                .filter(nickname -> nickname != null && !nickname.trim().isEmpty()) // 过滤 null/空
                .collect(Collectors.joining(","));               // 用逗号拼接
        reqVO.setSolveUserName(dutyUserName);
    }

    public void setDuration(FeedbackDO feedbackDO) {


// 问题关闭日期
        Date problemCloseDate = feedbackDO.getProblemCloseDate();
// 上板日期不会为空
        Date boardDate = feedbackDO.getBoardtDate();

// 将 java.util.Date 转换为 LocalDate
        LocalDate boardLocalDate = boardDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate;

        if (problemCloseDate != null) {
            endLocalDate = problemCloseDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } else {
            // 问题未关闭，使用今天日期
            endLocalDate = LocalDate.now();
        }

// 计算两个日期之间的天数差（包含起始日或不包含可根据业务调整）
        Integer duration = Math.toIntExact(ChronoUnit.DAYS.between(boardLocalDate, endLocalDate));
        feedbackDO.setDuration(duration);
    }

    public void sendKeepMessage(List<Long> dutyUserId) {
        //推送消息
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String userIds = "";
        StringBuilder userIdBuilder = new StringBuilder();


        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);

        for (AdminUserDO user : userList) {
            // 1. 推送系统消息 准备参数
            String templateCode = "warning-6"; // 站内信模版，记得在【站内信管理】中配置噢
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("planDate", formattedNow);
            NotifySendSingleToUserReqDTO sendToUserDTO = new NotifySendSingleToUserReqDTO();
            sendToUserDTO.setUserId(user.getId());
            sendToUserDTO.setTemplateCode(templateCode);
            sendToUserDTO.setTemplateParams(templateParams);

            String userId = weComMessageUtil.getUserIdByMobile(user.getEnterpriseWeChatAccount());
            if (userId != null && !userId.trim().isEmpty()) {
                // 如果已经有内容了，先添加分隔符
                if (userIdBuilder.length() > 0) {
                    userIdBuilder.append("|");
                }
                userIdBuilder.append(userId);
            }
        }

        // 将 StringBuilder 转换为最终的字符串
        userIds = userIdBuilder.toString();
        // 可选：检查最终结果是否为空
        if (userIds.isEmpty()) {
            // 处理没有找到任何有效用户ID的情况
            System.out.printf("没有找到任何有效的企业微信 UserID");
            return;
        }

        // 1. 使用 sendTextMessage 方法 (更灵活，可以同时指定用户、部门、标签)

        //从字典配置中获取发送的消息
        DictDataDO wxMessage = dictDataService.getDictData("by_message", "4");

        String text = wxMessage.getLabel();

        String systemMessage = text + formattedNow;
        // 将时间戳添加到消息中
        WeComMessageUtil.WeComSendResult weComSendResult = weComMessageUtil.sendTextMessage(systemMessage, userIds, null, null);
        System.out.printf("推送结果:" + weComSendResult.toString());

    }



}